package com.yt.sys.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.sys.mapper.SysRoleMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.yt.sys.mapper.SysUserMapper;
import com.yt.sys.mapper.SysUserRoleMapper;
import com.yt.sys.models.dto.SysRoleDTO;
import com.yt.sys.models.dto.SysUserDTO;
import com.yt.sys.models.dto.SysUserRoleDTO;
import com.yt.sys.models.bo.SysUserSaveBO;
import com.yt.sys.models.service.ISysUserService;
import com.yt.sys.common.config.YmlConfig;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDTO> implements ISysUserService {

    @Autowired
    private YmlConfig ymlConfig;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public boolean add(SysUserSaveBO saveBO) {
        SysUserDTO dto = new SysUserDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(ymlConfig.getPkId());
        return this.insert(dto);
    }

    @Override
    public List<SysRoleDTO> getUserRoles(Long userId) {
        // 查询用户角色关联
        EntityWrapper<SysUserRoleDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId);
        List<SysUserRoleDTO> userRoles = sysUserRoleMapper.selectList(wrapper);

        // 提取角色ID
        List<Long> roleIds = userRoles.stream()
                .map(SysUserRoleDTO::getRoleId)
                .collect(Collectors.toList());

        // 查询角色信息
        if (roleIds.isEmpty()) {
            return Collections.emptyList();
        }
        return sysRoleMapper.selectBatchIds(roleIds);
    }

    @Override
    public boolean assignRoles(Long userId, List<Long> roleIds) {
        // 先删除原有关联
        EntityWrapper<SysUserRoleDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userId);
        sysUserRoleMapper.delete(wrapper);

        // 添加新关联
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Long roleId : roleIds) {
                SysUserRoleDTO userRole = new SysUserRoleDTO();
                userRole.setId(ymlConfig.getPkId());
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                sysUserRoleMapper.insert(userRole);
            }
        }
        return true;
    }
}